<template>
  <div class="user-management-container">
    <div class="page-header">
      <h1>用户管理</h1>
      <el-button type="primary" @click="openAddUserDialog">
        <Plus /> 新增用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-table 
      :data="filteredUsers" 
      border 
      style="width: 100%; margin-bottom: 20px;"
      highlight-current-row
    >
      <el-table-column 
        prop="id" 
        label="ID" 
        width="80" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="name" 
        label="姓名" 
        width="120"
      ></el-table-column>
      <el-table-column 
        prop="email" 
        label="邮箱"
      ></el-table-column>
      <el-table-column 
        prop="role" 
        label="角色" 
        width="120"
      ></el-table-column>
      <el-table-column 
        prop="status" 
        label="状态" 
        width="100" 
        align="center"
      >
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
            {{ scope.row.status === 'active' ? '活跃' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
        prop="createdAt" 
        label="创建时间" 
        width="180"
      ></el-table-column>
      <el-table-column 
        label="操作" 
        width="180" 
        align="center"
      >
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary" 
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="users.length"
      ></el-pagination>
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog 
      :title="isEditMode ? '编辑用户' : '新增用户'" 
      v-model="dialogVisible"
      width="500px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="userForm"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="访客" value="visitor"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditMode">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitForm"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue';
import { Plus } from '@element-plus/icons-vue';

// 获取Element Plus的消息提示组件
const { proxy } = getCurrentInstance();
const ElMessage = proxy.$message;

// 模拟用户数据
const users = ref([
  {
    id: 1,
    name: '张三',
    email: 'zhangsan@example.com',
    role: 'admin',
    status: 'active',
    createdAt: '2023-01-15'
  },
  {
    id: 2,
    name: '李四',
    email: 'lisi@example.com',
    role: 'user',
    status: 'active',
    createdAt: '2023-02-20'
  },
  {
    id: 3,
    name: '王五',
    email: 'wangwu@example.com',
    role: 'user',
    status: 'inactive',
    createdAt: '2023-03-05'
  },
  {
    id: 4,
    name: '赵六',
    email: 'zhaoliu@example.com',
    role: 'visitor',
    status: 'active',
    createdAt: '2023-03-18'
  },
  {
    id: 5,
    name: '钱七',
    email: 'qianqi@example.com',
    role: 'user',
    status: 'active',
    createdAt: '2023-04-02'
  },
  {
    id: 6,
    name: '孙八',
    email: 'sunba@example.com',
    role: 'visitor',
    status: 'inactive',
    createdAt: '2023-04-25'
  },
  {
    id: 7,
    name: '周九',
    email: 'zhoujiu@example.com',
    role: 'user',
    status: 'active',
    createdAt: '2023-05-10'
  },
  {
    id: 8,
    name: '吴十',
    email: 'wushi@example.com',
    role: 'admin',
    status: 'active',
    createdAt: '2023-05-22'
  }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);

// 对话框相关
const dialogVisible = ref(false);
const isEditMode = ref(false);
const currentEditId = ref(null);

// 表单数据
const form = ref({
  name: '',
  email: '',
  role: '',
  status: 'active',
  password: ''
});

// 表单验证规则
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ]
});

// 计算属性 - 分页后的数据
const filteredUsers = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return users.value.slice(startIndex, startIndex + pageSize.value);
});

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 打开新增用户对话框
const openAddUserDialog = () => {
  isEditMode.value = false;
  currentEditId.value = null;
  // 重置表单
  form.value = {
    name: '',
    email: '',
    role: '',
    status: 'active',
    password: ''
  };
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  isEditMode.value = true;
  currentEditId.value = row.id;
  // 填充表单数据
  form.value = {
    name: row.name,
    email: row.email,
    role: row.role,
    status: row.status,
    password: '' // 编辑时不显示密码
  };
  dialogVisible.value = true;
};

// 删除用户
const handleDelete = (row) => {
  users.value = users.value.filter(user => user.id !== row.id);
  // 显示删除成功提示
  ElMessage.success('用户已删除');
};

// 提交表单
const submitForm = () => {
  // 表单验证
  if (!form.value.name) {
    ElMessage.error('请输入姓名');
    return;
  }
  if (!form.value.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.value.email)) {
    ElMessage.error('请输入正确的邮箱格式');
    return;
  }
  if (!form.value.role) {
    ElMessage.error('请选择角色');
    return;
  }
  if (!isEditMode.value && (!form.value.password || form.value.password.length < 6)) {
    ElMessage.error('密码长度不能少于6个字符');
    return;
  }

  if (isEditMode.value) {
    // 编辑现有用户
    const index = users.value.findIndex(user => user.id === currentEditId.value);
    if (index !== -1) {
      users.value[index] = {
        ...users.value[index],
        name: form.value.name,
        email: form.value.email,
        role: form.value.role,
        status: form.value.status
      };
      ElMessage.success('用户已更新');
    }
  } else {
    // 添加新用户
    const newId = Math.max(...users.value.map(u => u.id), 0) + 1;
    users.value.push({
      id: newId,
      ...form.value,
      createdAt: new Date().toLocaleDateString()
    });
    ElMessage.success('新用户已添加');
  }

  dialogVisible.value = false;
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}
</style>
    